﻿using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Topshelf;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Topshelf.Autofac;
using Topshelf.Logging;

using Topshelf.Demo.Repositories;
using Topshelf.Demo.IRepositories;
using Topshelf.Demo.Jobs;
using Topshelf.Demo.Services;
using Topshelf.Demo.Domain;

namespace Topshelf.Demo
{
    class Program
    {
        public static IConfigurationRoot Configuration;

        static void Main(string[] args)
        {
            var configPath = Path.Combine(AppContext.BaseDirectory,  "configs");
            var builderConfig = new ConfigurationBuilder()
                .SetBasePath(configPath)
                .AddJsonFile("appsettings.json", optional: true);
            Configuration = builderConfig.Build();
            ServiceOption serviceOption = Configuration.GetSection("service").Get<ServiceOption>();

            var serviceProvider = new ServiceCollection()
                .AddSingleton(Configuration);

            var builder = new ContainerBuilder();
            builder.Populate(serviceProvider);
            builder.RegisterType<SampleRepository>().As<ISampleRepository>();
            builder.RegisterType<SampleService>();
            builder.RegisterType<SampleJob>();
            var container = builder.Build();

            HostFactory.Run(c =>
            {
                c.UseLog4Net(Path.Combine(configPath,  "log4net.config"));
                c.UseAutofacContainer(container);

                c.Service<SampleService>(s =>
                {
                    // Let Topshelf use it
                    s.ConstructUsingAutofacContainer();
                    s.WhenStarted((service, control) => service.Start());
                    s.WhenStopped((service, control) => service.Stop());        
                });

                c.SetServiceName(serviceOption.ServiceName);
                c.SetDisplayName(serviceOption.DisplayName);
                c.SetDescription(serviceOption.Description);
            });
        }
    }
}
